<template>
    <div class="list-box">
        <div class="pannel-title pannel-between">
            <div>角色列表</div>
            <a-button class="pannel-btn" size="small" type="primary" shape="round" @click="addAdmin()">
                <PlusCircleFilled />
                新增角色
            </a-button>
        </div>
        <div class="line"></div>
        <div class="data-table">
            <a-table
                :columns="columns"
                :row-key="(record) => record.id"
                :data-source="dataSource"
                :pagination="pagination"
                :loading="isLoading"
                @change="handleTableChange"
            >
                <template #status="{text}">
                    <span class="span-green" v-if="text === 'Enabled'">已启用</span>
                    <span class="span-red" v-if="text === 'Disabled'">已禁用</span>
                </template>
                <template #action="{record}">
                    <a @click="editAdmin(record)" title="编辑" style="margin-right:5px;"><img src="@/assets/images/cz-edit.png"/></a>
                    <a @click="deleteAdmin(record)" title="删除"><img src="@/assets/images/cz-delete.png"/></a>
                </template>
            </a-table>
            <a-modal v-model:visible="visible" :maskClosable="false" :afterClose="closeModal">
                <h3 class="modal-title">{{validate.form.id ? '修改':'新增'}}</h3>
                <div class="modal-form">
                    <div class="modal-form-item">
                        <label class="required">角色名称</label>
                        <div class="modal-input"><a-input v-model:value="validate.form.name" :class="{'input-invalid':!validate.rules.name.$valid && validate.rules.name.$dirty}" placeholder="请输入用户名" /></div>
                    </div>
                    <div class="modal-form-item">
                        <label class="required">状态</label>
                        <div class="modal-input">
                            <a-select v-model:value="validate.form.status" style="width: 240px">
                                <a-select-option value="Enabled">启用</a-select-option>
                                <a-select-option value="Disabled">禁用</a-select-option>
                            </a-select>
                        </div>
                    </div>
                </div>
                <template #footer>
                    <div class="modal-btn">
                        <a-button type="default" shape="round" @click="cancel()">取消</a-button>
                        <a-button type="primary" shape="round" @click="confirm()">确定</a-button>
                    </div>
                </template>
            </a-modal>
        </div>
    </div>
</template>
<script>
import { PlusCircleFilled } from "@ant-design/icons-vue";
import { useStore } from "vuex";
import { watch } from "vue";
import { reactive, ref } from "@vue/reactivity";
import { message, Table, Modal } from "ant-design-vue";
import httpRequest from "@/util/httpRequest";
import Validate from "@/util/validate";
export default {
    components: {
        PlusCircleFilled,
        ATable: Table,
    },
    setup() {
        const store = useStore();
        //text：页面头部面包屑的显示文字，isBack：是否显示页面头部返回按钮
        store.dispatch("setBreadcrumb", { text: "系统设置 / 角色管理", isBack: false });
        const dataSource = ref([]);
        const validate = reactive(new Validate({
            id:[null],
            name:["",[Validate.Required()]],
            status:["Enabled",[]],
        }));
        watch(() =>  validate.form.loginId, () => {
            validate.Validity('loginId');
        })
        watch(() =>  validate.form.name, () => {
            validate.Validity('name');
        })
        const columns = reactive([
            {
                title: "ID",
                dataIndex: "id",
                key: "id",
            },
            {
                title: "角色名称",
                dataIndex: "name",
                key: "name",
            },
            {
                title: "创建日期",
                dataIndex: "createTime",
                key: "createTime",
            },
            {
                title: "状态",
                dataIndex: "status",
                key: "status",
                slots: { customRender: "status" },
            },
            {
                title: "操作",
                key: "action",
                slots: { customRender: "action" },
            },
        ]);
        const pagination = reactive({
            current: 1,
            pageSize: 10,
            total: 0,
        });
        return {
            dataSource,
            columns,
            pagination,
            isLoading: ref(false),
            visible: ref(false),
            validate
        };
    },
    data() {
        return {
            closeModal:()=>{
                this.validate.resetValue();
                this.$nextTick(()=>{
                    this.validate.resetValid();
                })
            }
        };
    },
    mounted() {
        this.getList();
    },
    methods: {
        getList() {
            this.isLoading = true;
            httpRequest
                .post("角色列表", { pageNo: this.pagination.current })
                .then((res) => {
                    this.dataSource = res.data.list;
                    this.pagination.total = res.data.pages * 10;
                })
                .finally(() => {
                    this.isLoading = false;
                });
        },
        handleTableChange(page) {
            this.pagination.current = page.current;
            this.getList();
        },
        deleteAdmin(item) {
            Modal.confirm({
          title: '系统提示',
          content: '确认删除当前角色？',
          okText: '确认',
          cancelText: '取消',
          onOk:()=>{
              return new Promise((res)=>{
                  httpRequest
                  .post("删除角色", { roleId: item.id })
                  .then(() => {
                    message.warning('删除角色成功！');
                    this.getList();
                  })
                  .catch(()=>{
                    message.warning({content:"角色删除失败",key:'error'})
                  })
                  .finally(() => {
                    this.isLoading = false;
                    res();
                  });
              })
          }
      })
            console.log(item);
        },
        editAdmin(item) {
            this.visible = true;
            this.validate.setValue(item);
        },
        cancel() {
            this.visible = false;
        },
        addAdmin(){
            this.visible = true;
        },
        confirm(){
            if(this.validate.UpdateValidate()){
                const url = this.validate.form.id ? '编辑角色':'创建角色';
                const msg = this.validate.form.id ? '修改成功':'创建成功';
                this.validate.form.pageIds=[];
                let user = JSON.parse(localStorage.getItem("user"));
                console.log(user)
                console.log(user.auths)
                let userAuths = user.auths;
                for (let i = 0; i < userAuths.length; i++) {
                    const auth = userAuths[i];
                    this.validate.form.pageIds.push(auth.id);
                }
                // this.validate.form.ids= this.validate.form.ids.join();
                this.validate.form.remark='';
                httpRequest.post(url,this.validate.form).then(()=>{
                    this.visible = false;
                    message.success(msg);
                });
            }else{
                console.log(this.validate.rules);
            }
        }
    },
};
</script>
<style lang="less" scoped>
.line {
    width: 100%;
    margin: 20px 0;
    border-top: 1px solid #eee;
}
.span-green {
    display: flex;
    align-items: center;
    &:before {
        content: "";
        display: block;
        width: 4px;
        height: 4px;
        border-radius: 2px;
        margin-right: 5px;
        background: #14ce79;
    }
}
.span-red {
    display: flex;
    align-items: center;
    &:before {
        content: "";
        display: block;
        width: 4px;
        height: 4px;
        border-radius: 2px;
        margin-right: 5px;
        background: #fe4e50;
    }
}
</style>
